// api
import {
  checkNickname,
  checkPhone,
  checkEmail,
  sendMail,
  sendSMS,
} from '@/api/passport';

export async function verifyCheckNickname(target) {
  console.log(this);
  const { nickname } = target;
  const regexpNickname = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
  if (nickname.value.trim() === '') {
    nickname.tip = '';
    return;
  }
  if (!regexpNickname.test(nickname.value)) {
    nickname.tip = '昵称格式不正确';
    nickname.state = false;
    return;
  }
  const res = await checkNickname({ nickname: nickname.value });
  nickname.tip = res.message;
  if (res.code === 400) {
    nickname.tip = '该昵称不可用';
  }
  if (res.code !== 200) {
    nickname.state = false;
    return;
  }
  nickname.state = true;
}

export async function verifyCheckSign(target) {
  const { sign } = target;
  const regexPhone = /^[1]([3-9])[0-9]{9}$/;
  const regexEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
  if (regexPhone.test(sign.value)) {
    sign.state = true;
    sign.tip = '';
    sign.signType = 'phone'; // 这个就表示可获得验证码的类型
    return;
  }
  if (regexEmail.test(sign.value)) {
    sign.state = true;
    sign.tip = '';
    sign.signType = 'email'; // 这个就表示可获得验证码的类型
    return;
  }
  sign.state = false;
  sign.signType = null;
}

async function verifySign(target) {
  const { sign } = target;
  const funObj = {
    phone: checkPhone,
    email: checkEmail,
  };
  const { signType } = sign;
  const options = {};
  options[signType] = sign.value;
  const { code, message } = await funObj[signType](options);
  sign.tip = message;
  sign.state = code === 200;
  return code === 200;
}

export async function getVerifycode(target) {
  const { nowAction, sign, verifycode } = target;
  verifycode.sending = true;
  if (nowAction === 'register' && !(await verifySign(target))) {
    // 在注册操作下,先验证帐号是否可用
    verifycode.sending = false;
    return;
  }
  const funObj = {
    phone: sendSMS,
    email: sendMail,
  };
  const { signType } = sign;
  const options = {};
  options[signType] = sign.value;
  const { code, message, data } = await funObj[signType](options);
  verifycode.tip = message;
  verifycode.state = code === 200;
  verifycode.sending = false;
  try {
    verifycode.expiresIn = data.verifyCode.expiresIn;
  } catch (error) {
    verifycode.expiresIn = data;
  }
  // 这里expiresIn是肯定会有一个时间戳的
  const timer = setInterval(() => {
    const computeCD = Number(Date.now()) - Number(verifycode.expiresIn);
    const CD = 120 - Math.floor(computeCD / 1000);
    if (CD > 0) {
      verifycode.tip = `验证码的CD还有: ${CD}s`;
    } else {
      verifycode.tip = '';
      clearInterval(timer);
    }
  }, 1000);
}

export async function verifyCheckPassword(target) {
  const { password } = target;
  const regexPassword = /^\w{6,16}$/;
  if (!regexPassword.test(password.value)) {
    password.tip = '密码格式为6-16个字符组成，区分大小写';
    password.state = false;
  } else {
    password.tip = '';
    password.state = true;
  }
}
